<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Repository;

use Doctrine\ORM\EntityRepository;
use Goods\Entity\GoodsClass;
use Goods\Entity\GoodsInClass;
use function Doctrine\ORM\QueryBuilder;

class GoodsClassRepository extends EntityRepository
{
    /**
     * 分类列表（后台）
     * @return int|mixed|string
     */
    public function findClassList()
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('c')
            ->addSelect('(SELECT COUNT(i.inId) FROM '.GoodsInClass::class.' AS i WHERE i.classId = c.classId) AS goodsNum')
            ->from(GoodsClass::class, 'c')
            ->orderBy('c.classTopId', 'ASC')->addOrderBy('c.classSort', 'ASC');

        return $query->getQuery()->getResult();
    }

    /**
     * 查询商品子分类
     * @param $str
     * @return mixed
     */
    public function findClassSub($str)
    {
        return $this->getEntityManager()->createQueryBuilder()
            ->select('c')
            ->from(GoodsClass::class, 'c')
            ->where('c.classPath LIKE :word')
            ->setParameter('word', $str . '%')
            ->getQuery()->getResult();
    }

    /*==============================================下面为前台调用==============================================*/

    /**
     * 商品分类面包屑
     * @param GoodsClass $goodsClass
     * @return int|mixed|string
     */
    public function shopClassBreadcrumbs(GoodsClass $goodsClass)
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('c')
            ->from(GoodsClass::class, 'c')
            ->where($query->expr()->in('c.classId', $goodsClass->getClassPath()))
            ->orderBy('c.classPath', 'ASC');

        return $query->getQuery()->getResult();
    }
}